package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Jwt 工具类.
 *
 * @author 宫新程
 * @since 2019/3/16 13:36
 */
@ConfigurationProperties("jwt.config")
public class JwtUtil {

  private String key;

  private long ttl; // 一个小时

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public long getTtl() {
    return ttl;
  }

  public void setTtl(long ttl) {
    this.ttl = ttl;
  }

  /**
   * 生成JWT.
   *
   * @param id 主键id
   * @param subject 用户名称标识
   * @return Token令牌
   */
  public String createJWT(String id, String subject, String roles) {
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    JwtBuilder builder =
        Jwts.builder()
            .setId(id)
            .setSubject(subject)
            .setIssuedAt(now)
            .signWith(SignatureAlgorithm.HS256, key)
            .claim("roles", roles);
    if (ttl > 0) {
      builder.setExpiration(new Date(nowMillis + ttl));
    }
    return builder.compact();
  }

  /**
   * 解析JWT.
   *
   * @param jwtStr token串
   * @return Claims
   */
  public Claims parseJWT(String jwtStr) {
    try {
      return Jwts.parser().setSigningKey(key).parseClaimsJws(jwtStr).getBody();
    } catch (ExpiredJwtException e) {
      throw new RuntimeException("token已过期, 请重新获取");
    } catch (Exception e) {
      throw new RuntimeException("令牌不正确");
    }
  }
}
